const { Service } = require('egg');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const svgCaptcha = require('svg-captcha');
class UserService extends Service {
  async login(username, password, captcha) {
    if (!this.ctx.session.captcha) {
      this.ctx.status = 400;
      this.ctx.body = { message: '验证码未提供' };
      return;
    }
    if (captcha.toLowerCase() !== this.ctx.session.captcha.toLowerCase())
      this.ctx.throw(400, '验证码错误');
    const user = await this.app.mysql.get('user', { username });
    if (!user || !bcrypt.compareSync(password, user.password))
      this.ctx.throw(401, '用户名或密码错误');
    // 签发双 Token
    const payload = { uid: user.id, username };
    const token = jwt.sign(payload, this.app.config.jwt.secret, {
      expiresIn: this.app.config.jwt.expiresIn,
    });
    const refreshToken = jwt.sign(payload, this.app.config.jwt.refreshSecret, {
      expiresIn: this.app.config.jwt.refreshExpiresIn,
    });

    this.ctx.body = { user,status:200, token, refreshToken, message: '登录成功' };
  }

  async register(username, password) {
    if (await this.app.mysql.get('user', { username })) {
      this.ctx.throw(400, '用户名已存在');
    }
    const hashedPassword = bcrypt.hashSync(password, 10);
    const user = { username, password: hashedPassword, created_at: new Date() };
    const res = await this.app.mysql.insert('user', user);
    this.ctx.body = { id: res.insertId, username };
  }
}

module.exports = UserService;
